/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Records.Database;

import Records.Attributes.LibraryDataSets;
import Records.UserInterface.SplashClass;
import Records.Database.DBSQL;
import Records.Attributes.LibraryMetadataExtract;
import Records.Main.RecordsMain;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Alexander
 */
public class updateLibrary implements Runnable {

    static ArrayList paths;

    private volatile boolean running = true;

    public void terminate() {
        System.out.println("updateLibrary.terminate()");
        running = false;
    }

    @Override
    public void run() {
        System.out.println("updateLibrary.run()");
        DefaultTableModel model = (DefaultTableModel) RecordsMain.getUI().userLibrary.getModel();
        if (model.getRowCount() != 0) {
            ResultSet res = null;
            try {
                res = RecordsMain.dba.getLibDirectory();
            } catch (SQLException ex) {
                Logger.getLogger(updateLibrary.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
            String Dir = null;
            try {
                if (res.next()) {
                    Dir = res.getString("Directory");
                    //System.out.println(Dir);
                } else {
                    //System.err.println("No Directory!");
                }
                res.close();

            } catch (SQLException ex) {
                Logger.getLogger(updateLibrary.class.getName()).log(Level.SEVERE, null, ex);
            }
            while (running) {
                System.out.println("Updating");
                try {
                    paths = new ArrayList(RecordsMain.getFilePathList());
                    System.out.println("Counting Files");
                    countDirectoryFiles(new File(Dir));
                    if (!paths.isEmpty()) {
                        deleteFile();
                    }
                    System.out.println("Sleeping...");
                    Thread.sleep((long) 10000);
                } catch (InterruptedException e) {
                    Logger.getLogger(SplashClass.class.getName()).log(Level.SEVERE, null, e);
                    running = false;
                }
            }
        }
    }

    static void countDirectoryFiles(File topFile) {
        System.out.println("updateLibrary.countDirectoryFiles(" + topFile + ")");
        if (topFile.isDirectory()) {
            for (File f : topFile.listFiles()) {
                countDirectoryFiles(f);
            }
        } else if (topFile.isFile()) {
            if (paths.contains(topFile.getAbsolutePath())) {
                paths.remove(topFile.getAbsolutePath());
            } else {
                addFile(topFile.getAbsolutePath());
            }
        }
    }

    public static void addFile(String filePath) {
        System.out.println("updateLibrary.addFile(" + filePath + ")");

        LibraryMetadataExtract metadata;
        if (FilenameUtils.isExtension(filePath, "m4a") || FilenameUtils.isExtension(filePath, "mp3")) {
            metadata = new LibraryMetadataExtract(new File(filePath));
            LibraryDataSets LDS = new LibraryDataSets(metadata.extract());
            LDS.InsertLibraryData();
            RecordsMain.clearFilePathList();
            ResultSet res = RecordsMain.dba.getAllFilePaths();
            try {
                while (res.next()) {
                    String fPath = res.getString("Filepath");
                    RecordsMain.addToFilePathList(fPath);
                    System.out.println("Adding file to list: " + fPath);
                }
            } catch (SQLException ex) {
                Logger.getLogger(DBSQL.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void deleteFile() {
        System.out.println("updateLibrary.deleteFile()");

        DefaultTableModel model = (DefaultTableModel) RecordsMain.getUI().userLibrary.getModel();
        String ID = null;
        for (int x = 0; x < paths.size(); x++) {
            try (ResultSet Result = RecordsMain.dba.getIDByPath(paths.get(x).toString())) {
                if (Result.next()) {
                    ID = Result.getString("Song_ID");
                    ResultSet results = RecordsMain.dba.SearchLibByID(ID);
                    try {
                        // While there are more results to process
                        if (results.next()) {
                            String title = results.getString("SONG_TITLE");
                            String artist = results.getString("ARTIST");
                            String album = results.getString("ALBUM");
                            String genre = results.getString("GENRE");

                            for (int y = 0; y < model.getRowCount(); y++) {
                                if (model.getValueAt(y, 0).equals(title) && model.getValueAt(y, 1).equals(artist) && model.getValueAt(y, 2).equals(album) && model.getValueAt(y, 3).equals(genre)) {
                                    //System.out.println("Removing Row!");
                                    model.removeRow(y);
                                    RecordsMain.dba.deleteByID("LibSongs", ID);
                                    RecordsMain.dba.deleteByID("LibAlbums", ID);
                                    RecordsMain.dba.deleteByID("LibArtists", ID);
                                    RecordsMain.dba.deleteByID("LibFilePaths", ID);
                                }
                            }
                            RecordsMain.getUI().NumSongs.setText("" + model.getRowCount() + " Songs");
                        }
                        results.close();

                    } catch (SQLException ex) {
                        Logger.getLogger(updateLibrary.class
                                .getName()).log(Level.SEVERE, null, ex);
                    }
                    RecordsMain.clearFilePathList();
                    ResultSet res = RecordsMain.dba.getAllFilePaths();
                    try {
                        while (res.next()) {
                            String fPath = res.getString("Filepath");
                            RecordsMain.addToFilePathList(fPath);

                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(DBSQL.class
                                .getName()).log(Level.SEVERE, null, ex);
                    }

                }
            } catch (SQLException ex) {
                Logger.getLogger(updateLibrary.class
                        .getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}
